﻿using ECMS.AppService.Model.Models;
using ECMS.AppService.Model.Requests;
using ECMS.AppService.Model.Responses;
using ECMS.Domain.Models;
using ECMS.Infrastructure.ClientData;
using ECMS.Infrastructure.Domain;
using ECMS.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ECMS.AppService.Implements
{
    public partial class MenuService
    {
        public async Task<ApiResult<SaveResponse>> SaveAsync(MenuModel model)
        {
            var response = new ApiResult<SaveResponse>();
            try
            {
                if (model == null)
                    throw new ArgumentNullException(nameof(model));
                Menu entity;
                if (model.Guid == null)
                {
                    entity = new Menu
                    {
                        Open = model.Open,
                        Icon = model.Icon,
                        Pid = model.Pid,
                        Path = model.Path,
                        Remark = model.Remark,
                        Title = model.Title
                    };
                    await _unitofwork.RegisterNewAsync(entity);
                }
                else
                {
                    entity = await Query().FirstOrDefaultAsync(p => p.Guid == model.Guid);
                    if (entity == null)
                    {
                        response.Message = "找不到要修改的数据.";
                        return response;
                    }
                    entity.Open = model.Open;
                    entity.Icon = model.Icon;
                    entity.Pid = model.Pid;
                    entity.Path = model.Path;
                    entity.Remark = model.Remark;
                    entity.Title = model.Title;

                    _unitofwork.RegisterDirty(entity);
                }

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "保存成功." : "保存失败.";
                response.Data = new SaveResponse
                {
                    Guid = entity.Guid,
                    Id = entity.Id
                };
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        public async Task<ApiResult<Page<MenuResponse>>> GetPagesAsync(GetMenuPagesRequest request)
        {
            var response = new ApiResult<Page<MenuResponse>>();
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));

                // 读取数据
                var result = await Query()
                    .ToPageAsync(request.PageIndex, request.PageSize);

                if (result.Items == null || result.Items.Count == 0)
                {
                    response.Message = "暂无数据.";
                    return response;
                }
                response.Success = true;
                response.Message = "获取成功.";

                // 转换数据
                response.Data = result.ToViewPage(p => new MenuResponse
                {
                    Open = p.Open,
                    Icon = p.Icon,
                    Pid = p.Pid,
                    Path = p.Path,
                    Remark = p.Remark,
                    Title = p.Title,
                    CreateTime = p.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    Guid = p.Guid,
                    Id = p.Id,
                });
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        public async Task<ApiResult<MenuResponse>> GetDetailAsync(Guid guid)
        {
            var response = new ApiResult<MenuResponse>();
            try
            {
                if (guid == null)
                    throw new ArgumentNullException(nameof(guid));

                // 读取数据
                var single = await Query().FirstOrDefaultAsync(p => p.Guid == guid);

                if (single == null)
                {
                    response.Message = "找不到记录.";
                    return response;
                }
                response.Success = true;
                response.Message = "获取成功.";

                // 转换数据
                response.Data = new MenuResponse
                {
                    Open = single.Open,
                    Icon = single.Icon,
                    Pid = single.Pid,
                    Path = single.Path,
                    Remark = single.Remark,
                    Title = single.Title,
                    CreateTime = single.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    Guid = single.Guid,
                    Id = single.Id,
                };
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        public async Task<ApiResult<string>> DeleteAsync(Guid guid)
        {
            var response = new ApiResult<string>();
            try
            {
                if (guid == null)
                    throw new ArgumentNullException(nameof(guid));

                // 物理删除
                Delete(p => p.Guid == guid);

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "删除成功." : "删除失败.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }

        public async Task<ApiResult<IList<MenuRecursionResponse>>> GetListsWithRecursion()
        {
            var response = new ApiResult<IList<MenuRecursionResponse>>();
            try
            {

                // 读取数据
                var result = await Query().ToListAsync();

                var res = new List<MenuRecursionResponse>();
                GetChildren(result, res);

                response.Data = res;
                response.Success = true;
                response.Message = "获取成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }

        private void GetChildren(IList<Menu> menus, IList<MenuRecursionResponse> results, int pId = 0)
        {
            var result = menus.Where(p => p.Pid == pId).ToList();
            foreach (var child in result)
            {
                var res = new MenuRecursionResponse
                {
                    Title = child.Title,
                    Icon = child.Icon,
                    Id = child.Id,
                    Open = child.Open,
                    Path = child.Path,
                    Pid = child.Pid
                };
                if (menus.Any(p => p.Pid == child.Id))
                {
                    res.Children = new List<MenuRecursionResponse>();
                    GetChildren(menus, res.Children, child.Id);
                }
                results.Add(res);
            }
        }
    }
}
